package com.xijia.wuyouwallet.activity;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.xijia.wuyouwallet.MyApp;
import com.xijia.wuyouwallet.R;
import com.xijia.wuyouwallet.base.BaseActivity;
import com.xijia.wuyouwallet.utils.StringUtils;
import com.xijia.wuyouwallet.utils.UrlConfig;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.security.InvalidParameterException;

import cn.sharesdk.onekeyshare.OnekeyShare;

/**
 * Created by Administrator on 2017/7/13 0013.
 */

public class DimensionActivity extends BaseActivity implements View.OnClickListener{

    private ImageView dimension_code_back;
    private LinearLayout dimension_code_all;
    private TextView dimension_code_save;


    private WebView dimension_code_wv;
    private ProgressBar dimension_code_progressBar;


    private String cachPath;
    private File ImgDir;
    private   String path =null;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dimension_code);
        initView();
    }


    private void initView(){

        dimension_code_all = (LinearLayout) findViewById(R.id.dimension_code_all);
        dimension_code_back = (ImageView) findViewById(R.id.dimension_code_back);
        dimension_code_back.setOnClickListener(this);
        dimension_code_progressBar = (ProgressBar) findViewById(R.id.dimension_code_progressBar);
        dimension_code_wv = (WebView) findViewById(R.id.dimension_code_wv);
        dimension_code_save = (TextView) findViewById(R.id.dimension_code_save);
        dimension_code_save.setOnClickListener(this);

        dimension_code_wv.getSettings().setJavaScriptEnabled(true);
        //设置滚动条可见
        //setProgressBarIndeterminateVisibility(true);
        init();
        dimension_code_wv.addJavascriptInterface(new AndroidMessage(), "AndroidMessage");
        //Log.e("info","分享专属二维码="+UrlConfig.SHARE_DIMENSION_URL+"/id/"+ MyApp.userData.getData().getUser_id());
        dimension_code_wv.loadUrl(UrlConfig.SHARE_DIMENSION_URL+"/id/"+ MyApp.userData.getData().getUser_id());


        cachPath=getDiskCacheDir(this);

        //initData();
    }

    /*private void initData(){
        Map<String,Object> map = new HashMap<>();
        map.put("user",MyApp.userData.getData().getUser_id());
        showProgressDialog(true);
        XUtil.Post(UrlConfig.GET_EWCODE_URL,map,new MyCallBack<String>(){

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                dismissProgressDialog();
                //MyLogger.wLog().e("获取二维码result="+result);
                ErcodeData data = JSONObject.parseObject(result,ErcodeData.class);
                if (data.getCode()==200){
                    dimension_code_name.setText(data.getData().getName());
                    Picasso.with(DimensionActivity.this).load(data.getData().getQrcode()).fit().into(dimension_code_img);
                }else {
                    showToast(data.getMsg());
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                dismissProgressDialog();
            }
        });
    }*/

    private void init() {
        // TODO 自动生成的方法存根
        dimension_code_wv.setWebViewClient(new WebViewClient(){
            //覆写shouldOverrideUrlLoading实现内部显示网页
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // TODO 自动生成的方法存根
                //view.loadUrl(url);
                return false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                /*String title=view.getTitle();
                if(title==null){
                    title="";
                }
                common_wv_title.setText(title);*/
                super.onPageFinished(view, url);
            }
        });
        dimension_code_wv.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO 自动生成的方法存根
                dimension_code_progressBar.setVisibility(View.VISIBLE);
                dimension_code_progressBar.setProgress(newProgress);
                if (newProgress == 100) {
                    dimension_code_progressBar.setVisibility(View.GONE);
                }
                super.onProgressChanged(view, newProgress);
            }
        });
    }


    @Override
    public void onClick(View view) {

        switch (view.getId()){
            case R.id.dimension_code_back:
                finish();
                break;
            /*case R.id.dimension_code_share:
                showShare();
                break;*/
            case R.id.dimension_code_save:
                path = cachPath+"/"+ StringUtils.getBeijingTime()+"img.jpg";
                getScreenHot(dimension_code_all,path,true);
                break;
        }

    }
    /**
     * 截屏
     *
     */
    private void getScreenHot(View v, String filePath,boolean isToast)
    {
        try
        {
            Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas();
            canvas.setBitmap(bitmap);
            v.draw(canvas);

            try
            {
                FileOutputStream fos = new FileOutputStream(filePath);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                if (isToast){
                    showToast("图片已保存至"+cachPath);
                }
            }
            catch (FileNotFoundException e)
            {
                if (isToast){
                    showToast("图片保存失败");
                }
                throw new InvalidParameterException();
            }

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    public String getDiskCacheDir(Context context) {
        String cachePath = null;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            ImgDir = new File(Environment.getExternalStorageDirectory() + "/" + getResources().getString(R.string.app_name) + "/");
            if (!ImgDir.exists()) {
                ImgDir.mkdirs();
            }
            cachePath = ImgDir.getAbsolutePath();
        } else {
            cachePath = context.getCacheDir().getPath();
        }
        return cachePath;
    }

    class AndroidMessage{

        @JavascriptInterface
        public void share() {
            showShare();
        }
    }

    private void showShare() {
        OnekeyShare oks = new OnekeyShare();
        oks.disableSSOWhenAuthorize();
        oks.setTitle(getString(R.string.app_name));
        oks.setTitleUrl(UrlConfig.JOIN_US_URL+"/invite/"+ MyApp.userData.getData().getPhone());
        if (MyApp.systemData!=null){
            oks.setText(MyApp.systemData.getData().getList().getShare_words());
        }else {
            oks.setText("你的好友邀请你注册"+getString(R.string.app_name)+"app啦。。。");
        }
        oks.setUrl(UrlConfig.JOIN_US_URL+"/invite/"+ MyApp.userData.getData().getPhone());
        oks.setImageUrl(UrlConfig.FW_LOGON_URL);
        oks.show(this);
    }

}
